import services from '@/services/user';
import { EUser } from '@/services/user/UserController';
import { ProForm, ProFormText } from '@ant-design/pro-components';
import { message, Modal } from 'antd';
import React, { PropsWithChildren } from 'react';

const { addUserInfo } = services.UserController;
/**
 * 添加用户
 * @param fields
 */
const handleAdd = async (fields: EUser) => {
  const hide = message.loading('正在添加');
  try {
    const { success, errorMessage } = await addUserInfo(fields);
    hide();
    if (success) {
      message.success('添加成功');
      return true;
    } else {
      message.error(errorMessage);
      return false;
    }
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
interface CreateFormProps {
  modalVisible: boolean;
  onCancel: (show: boolean) => void;
  onReloadAndRest?: () => void;
}

const CreateForm: React.FC<PropsWithChildren<CreateFormProps>> = (props) => {
  const { modalVisible, onCancel, onReloadAndRest } = props;

  return (
    <Modal
      destroyOnClose
      title="会员新增"
      width={420}
      open={modalVisible}
      onCancel={() => onCancel(false)}
      footer={null}
    >
      <ProForm<EUser>
        onFinish={async (values) => {
          const success = await handleAdd(values);
          if (success) {
            onReloadAndRest?.();
          }
        }}
      >
        <ProFormText
          width="md"
          name="id"
          label="会员ID"
          disabled
          hidden={true}
        />
        <ProFormText
          width="md"
          name="name"
          label="会员名称"
          rules={[
            {
              required: true,
              message: '请输入会员名称',
            },
          ]}
        />
        <ProFormText
          width="md"
          name="phone"
          label="手机号码"
          rules={[
            {
              required: true,
              message: '请输入手机号码',
            },
          ]}
        />
      </ProForm>
    </Modal>
  );
};

export default CreateForm;
